package com.zqxq.lottery.service.user.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.controller.pay.IAlipayService;
import com.zqxq.lottery.entity.bo.product.ProductBO;
import com.zqxq.lottery.entity.o2o.product.UserProductO2O;
import com.zqxq.lottery.entity.po.product.ProductPO;
import com.zqxq.lottery.entity.po.sys.SysConfigPO;
import com.zqxq.lottery.entity.po.user.*;
import com.zqxq.lottery.entity.vo.product.ProductVO;
import com.zqxq.lottery.entity.vo.user.*;
import com.zqxq.lottery.mapper.product.ProductMapper;
import com.zqxq.lottery.mapper.sys.SysConfigMapper;
import com.zqxq.lottery.mapper.user.UserCashMapper;
import com.zqxq.lottery.mapper.user.UserFundsMapper;
import com.zqxq.lottery.mapper.user.UserInfoMapper;
import com.zqxq.lottery.mapper.user.UserProductMapper;
import com.zqxq.lottery.service.user.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 苦智
 * @date 2018/9/10 11:18
 * @description
 * @ClassName UserProductServiceImpl
 */
@Service
@Slf4j
public class UserProductServiceImpl extends ServiceImpl<UserProductMapper,UserProductPO> implements IUserProductService {
    private String msg_exchange = "您在%s成功兑换实物%s个，支付钻石%s个，钻石余额为%s。";
    private String msg_sale = "您在%s成功申请代卖换钱%s个，支付钻石%s个，钻石余额为%s。";
    @Autowired
    private UserFundsMapper userFundsMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private UserCashMapper userCashMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserAlipayService userAlipayService;
    @Autowired
    private IUserWechatService userWechatService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserFundsService userFundsService;
    @Autowired
    private IUserMsgService userMsgService;
    @Autowired
    private IAlipayService alipayService;
    @Override
    public List<UserProductTradVO> getUserProductPage(Page page, Map<String, Object> paramMap) {
        return baseMapper.selectUserProductPage(page,paramMap);
    }
    @Override
    public BigDecimal getUserProductTotalPrice(Map<String, Object> paramMap) {
        return baseMapper.getUserProductTotalPrice(paramMap);
    }


    @Override
    public UserProductTradDetailVO getUserProductDetail(String tradeId) {
        return baseMapper.getUserProductDetail(tradeId);
    }

    @Override
    public UserProductTradDetailVO getUserProduct(String tradeId) {
        return baseMapper.getUserProduct(tradeId);
    }

    @Override
    public Integer updateUserProductStatus(String tradeId, String logisticsNum, String logisticsCompany) {
        return baseMapper.updateUserProductStatus(tradeId,logisticsNum,logisticsCompany);
    }

    @Override
    public Integer updateReceivingInfo(UserAddressVO userAddressVO) {
        return baseMapper.updateReceivingInfo(userAddressVO);
    }

    @Override
    public Result save(HttpServletRequest request, UserProductVO vo) throws Exception {
        Result result = new Result();
        String payAccount = "";
        UserFundsPO userFundsPO = userFundsMapper.selectById(vo.getUserId());
        if(userFundsPO==null){
            return new Result(CodeEnum.FAIL.getCode(), "不存在此用户！");
        }
        ProductPO productPO = productMapper.selectById(vo.getProductId());
        if(productPO==null){
            return new Result(CodeEnum.FAIL.getCode(), "不存在此商品！");
        }
        SysConfigPO config = sysConfigMapper.getByKey("ZQXQ_DRAWCASH_CONFIG");
        if(config == null || Integer.valueOf(config.getCval())==0){
            return new Result(CodeEnum.FAIL.getCode(), "网络繁忙，请稍后再试！");
        }
        Long userId = Long.valueOf(vo.getUserId());
        UserInfoPO userInfo = userInfoMapper.selectById(userId);
        Integer enabled = userInfo.getEnabled();
        if(enabled==1){
            return new Result(CodeEnum.FAIL.getCode(),"抱歉，您的账户已被禁用,不能进行敏感操作！");
        }
        Integer isStatistic = userInfo.getIs_statistic();
        if(isStatistic==1){
            return new Result(CodeEnum.FAIL.getCode(),"抱歉，内部测试账号不能进行敏感操作！");
        }
        String exchangeMethod = vo.getExchangeMethod();
        if(Integer.valueOf(vo.getType())==2){
            if("0".equals(exchangeMethod)){
                UserAlipayPO alipayPO = userAlipayService.selectById(userId);
                if(alipayPO == null || StrUtils.isEmpty(alipayPO.getAlipay_account())){
                    return new Result(10000, "请绑定支付宝账号！");
                }
                //查询支付宝账号
                payAccount = alipayPO.getAlipay_account();
            } else if("1".equals(exchangeMethod)){
                UserWechatPO userWechatPO = userWechatService.selectById(userId);
                if(userWechatPO == null || StrUtils.isEmpty(userWechatPO.getOpen_id())){
                    return new Result(10001, "请绑定微信账号！");
                }
                //查询微信账号
                payAccount = userWechatPO.getOpen_id();
            } else {
                return new Result(CodeEnum.FAIL.getCode(), CodeEnum.FAIL_100002.getMsg());
            }
        }else if(Integer.valueOf(vo.getType())==1){
            if(StringUtils.isEmpty(userInfo.getAddress_id())){
                return new Result(10001, "兑换实物请添加收货地址！");
            }
        }
        BigDecimal price = productPO.getExchange_rate();
        BigDecimal diamonds = userFundsPO.getDiamonds();
        BigDecimal num = new BigDecimal(vo.getNum());
        if(num.compareTo(BigDecimal.ZERO)<=0){
            return new Result(CodeEnum.FAIL.getCode(), "数量必须大于0！");
        }
        BigDecimal totalPrice = price.multiply(num);
        if(diamonds.compareTo(totalPrice)==-1){
            return new Result(CodeEnum.FAIL.getCode(), "用户钻石不足！");
        }
        userFundsPO.setDiamonds(diamonds.subtract(totalPrice));
        vo.setId(String.valueOf(ymlConfig.getPkId()));
        UserProductPO po = UserProductO2O.toPO(vo);
        po.setPrice(price);
        SysConfigPO config2 = sysConfigMapper.getByKey("PRODUCT_DISCOUNT_RATE");
        String value2 = config2.getCval();
        po.setExchange_price(price.multiply(new BigDecimal(value2)));
        String key = "ADD_PRODUCT_ORDER_"+userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            return new Result(CodeEnum.FAIL.getCode(), "你还有未处理的订单，请稍后操作！");
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            if(Integer.valueOf(vo.getType())==2){
                po.setStatus(1);
            }
            Long cashId = ymlConfig.getPkId();
            UserCashPO userCashPO = new UserCashPO();
            userCashPO.setId(cashId);
            userCashPO.setUser_id(userInfo.getId());
            userCashPO.setReal_name(userInfo.getReal_name());
            userCashPO.setMobile(userInfo.getMobile());
            userCashPO.setPay_way(8);
            userCashPO.setPay_account(null);
            userCashPO.setType(10);
            userCashPO.setStatus(4);
            userCashPO.setPay_amount(totalPrice);
            userCashPO.setRemainder(userFundsPO.getDiamonds());
            //如果交易类型为代卖，直接企业转账到个人账户
            totalPrice = totalPrice.multiply(new BigDecimal(value2));
            if(totalPrice.compareTo(BigDecimal.ZERO)<=0){
                return new Result(CodeEnum.FAIL.getCode(), "共需消耗钻石数必须大于0！");
            }
            if(totalPrice.compareTo(new BigDecimal(5))<0){
                return new Result(CodeEnum.FAIL.getCode(), "共需消耗钻石数不能低于5！");
            }
            if(Integer.valueOf(vo.getType())==2){
//                totalPrice = new BigDecimal(0.1);
                if("0".equals(exchangeMethod)){
                    result = alipayService.saveTransferMoney(userId, cashId, totalPrice, payAccount);
                }else if("1".equals(exchangeMethod)){
                    result = userWechatService.saveTransferMoney(request,userId, cashId, totalPrice, payAccount);
                }
            }
            if (result.getCode()==0) {
                baseMapper.insert(po);
                userCashMapper.insert(userCashPO);
                userFundsMapper.updateById(userFundsPO);
                DateFormat df = DateFormat.getTimeInstance();//只显示出时分秒
                if(Integer.valueOf(vo.getType())==2){
                    userMsgService.saveUserMsg(userId,String.format(msg_exchange,df.format(new Date()),num,price.setScale(2,BigDecimal.ROUND_HALF_UP),userFundsPO.getDiamonds().setScale(2,BigDecimal.ROUND_HALF_UP)),5);
                }else if(Integer.valueOf(vo.getType())==1){
                    userMsgService.saveUserMsg(userId,String.format(msg_sale,df.format(new Date()),num,price.setScale(2,BigDecimal.ROUND_HALF_UP),userFundsPO.getDiamonds().setScale(2,BigDecimal.ROUND_HALF_UP)),5);
                }
            }
        }catch(Exception e){
            log.error(userId+"网络繁忙，请稍后再试！",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        result.setData(vo);
        return result;
    }
    @Override
    public Page queryPage(Long userId,Integer status,Integer pageNo,Integer pageSize) throws Exception {
        Page page = new Page(pageNo,pageSize);
        List<UserProductListVO> list = baseMapper.queryPage(page,userId,status);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<UserProductListVO> query(Long userId) throws Exception {
        List<UserProductListVO> list = baseMapper.query(userId);
        return list;
    }

    @Override
    public List<UserProductTradExcelVO> getUserProductList(Map<String, Object> paramMap) {
        return baseMapper.getUserProductList(paramMap);
    }
    @Override
    public Result cancelUserProduct(String id) {
        Result result = new Result();
        UserProductPO userProductPO = baseMapper.selectById(id);
        if(userProductPO==null){
            return new Result(CodeEnum.FAIL.getCode(), "此订单不存在！");
        }
        if(userProductPO.getStatus()==3){
            return new Result(CodeEnum.FAIL.getCode(), "此订单已取消，请勿重复操作！");
        }
        if(userProductPO.getType()==2){
            return new Result(CodeEnum.FAIL.getCode(), "代卖换钱订单不允许取消！");
        }
        String key = "CALCEL_PRODUCT_ORDER_"+id;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            return new Result(CodeEnum.FAIL.getCode(), "你还有未处理的订单，请稍后操作！");
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            userProductPO.setId(Long.valueOf(id));
            userProductPO.setStatus(3);
            baseMapper.updateById(userProductPO);
            UserFundsPO userFundsPO = userFundsMapper.selectById(userProductPO.getUser_id());
            UserInfoPO userInfo = userInfoMapper.selectById(userProductPO.getUser_id());
            BigDecimal diamonds = userFundsPO.getDiamonds();
            BigDecimal price = userProductPO.getExchange_price();
            BigDecimal num = new BigDecimal(userProductPO.getNum());
            BigDecimal totalPrice = price.multiply(num);
            userFundsPO.setDiamonds(diamonds.add(totalPrice));
            Long cashId = ymlConfig.getPkId();
            UserCashPO userCashPO = new UserCashPO();
            userCashPO.setId(cashId);
            userCashPO.setUser_id(userInfo.getId());
            userCashPO.setReal_name(userInfo.getReal_name());
            userCashPO.setMobile(userInfo.getMobile());
            userCashPO.setPay_way(8);
            userCashPO.setPay_account(null);
            userCashPO.setType(5);
            userCashPO.setStatus(4);
            userCashPO.setPay_amount(totalPrice);
            userCashPO.setRemainder(userFundsPO.getDiamonds());
            userCashMapper.insert(userCashPO);
            userFundsMapper.updateById(userFundsPO);
        }catch(Exception e){
            log.error("订单"+id+"正在操作中，请稍后再试！",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return result;
    }

}
